<template>
  <el-container class="app-container">
    <el-collapse @change="handleCollapseChange" v-model="collapseActiveName">
      <el-collapse-item :title="collapseTitle" name="1">
        <el-tabs type="border-card">
          <el-form :model="pageInfo" ref="form" label-width="100px" size="medium">
            <el-row>
              <el-col :span="8" :offset="0">
                <el-form-item prop="realName" label="所属门店：">
                  <el-select v-model="pageInfo.storeId" clearable placeholder="请选择">
                    <el-option
                      v-for="item in storeListOptions"
                      :key="item.storeId"
                      :label="item.storeName"
                      :value="item.storeId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="realName" label="店员名称：">
                  <el-input v-model.trim='pageInfo.realName' placeholder="请输入店员名称"></el-input>
                </el-form-item>
              </el-col>
              <!--<el-col :span="8" :offset="0">
                <el-form-item prop="name" label="品牌状态：">
                  <el-radio-group v-model="pageInfo.enable">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>-->
              <el-col :span="5" :offset="0" class="tx-r">
                <el-button type="primary" icon="el-icon-search" @click='getData'>搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-tabs>
      </el-collapse-item>
    </el-collapse>
    <el-header>

    </el-header>

    <!--    <table-qh-head :publishStatus="pageInfo.enable" :total="total" :propsList="propsList" @tab-click="changeTab"/>-->
    <!--表格-->
    <table-view
      :columns="tableContent"
      :pageList="columnData"
      :templateDiv="{operation:true}"
      @sort-change="handleSortChange"
    >
      <template slot="operation" slot-scope="scope">
        <el-button size="mini" type="primary" @click="editBtnClick(scope.row ,'wxCode')">二维码</el-button>
      </template>
    </table-view>

    <!--分页-->
    <pagination-view :pagesize="pageInfo.pageSize"
                     :currentPage="pageInfo.pageNumber"
                     :total="total"
                     @size-change="sizeChange"
                     @current-change="pageChange"
    ></pagination-view>

    <el-dialog title="查看二维码" :visible.sync="dialogVisible" width="50%" :destroy-on-close="true">
      <el-row class="tx-c">
        <img :src="wxAppCode" alt="">
      </el-row>
      <el-row class="tx-c m-t-40">
        <a href="" download="" ref="downLoadTag"></a>
        <el-button type="primary" size="mimi" @click="saveImg">下载二维码</el-button>
      </el-row>
    </el-dialog>
  </el-container>
</template>

<script>
  import TableQhHead from '@/components/TableQhHead'
  import TableView from '@/components/TableView'
  import PaginationView from '@/components/PaginationView'

  import pageApi from '@/api/user/storeUser'
  import {getStorelist} from '@/api/system/offlineStoreManage'
  import {getWxappCode} from '@/api/common'

  export default {
    name: 'list',
    components: {
      TableQhHead,
      TableView,
      PaginationView
    },
    data() {
      return {
        storeListOptions: '',
        title: '添加',
        dialogVisible: false,
        wxAppCode: '',
        propsList: [{
          label: '启用',
          text: '启用',
          name: '1'
        }, {
          label: '禁用',
          text: '禁用',
          name: '0'
        }, {
          label: '全部',
          text: '全部',
          name: 'null'
        }],

        tableContent: [{
          field: 'storeUserId',
          label: 'ID'
        }, {
          field: 'realName',
          label: '昵称'
        }, {
          field: 'mobile',
          label: '手机号'
        }, {
          field: 'storeUserPost',
          label: '岗位'
        }, {
          field: 'storeName',
          label: '所属门店'
        }, {
          field: 'storeName1',
          label: '会员总数',
          sortable: true,
        }, {
          field: 'status',
          label: '状态'
        }, {
          field: 'operation',
          label: '操作'
        }],
        columnData: [],
        editBtnMapList: ['update', 'switchStatus'],  //自定义的按钮内容
        customWidth: "",
        pageInfo: {
          pageNum: 1,
          pageSize: 20,
          realName: '',
          storeId: '',
        },
        total: null,
        clickUser: {}
      }
    },
    watch: {},
    methods: {
      saveImg() {
        let {storeName, realName, mobile} = this.clickUser
        let fileName = `${storeName}_${realName}_${mobile}.png`
        const imgUrl = this.wxAppCode;
        // 如果浏览器支持msSaveOrOpenBlob方法，那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
          let bstr = atob(imgUrl.split(",")[1]);
          let n = bstr.length;
          let u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          let blob = new Blob([u8arr]);
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          // 这里就按照chrome等新版浏览器来处理
          let a = document.createElement("a");
          a.href = imgUrl;
          a.setAttribute("download", fileName);
          a.click();
        }
      },
      handleSortChange({prop, order}) {
        //1售价 2销量 3库存 4积分
        const orderByFilter = {
          salePrice: 1,
          salesCount: 2,
          totalStock: 3,
        }
        this.pageInfo.orderBy = orderByFilter[prop]
        this.pageInfo.sortType = (order === 'ascending' ? 0 : 1)
        this.getData()
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val
        this.getData()
      },
      // page变化函数
      pageChange(val) {
        this.pageInfo.pageNumber = val
        this.getData()
      },
      // 更改状态
      changeEnable(id, enable) {
        let _this = this
        pageApi.changeEnable(id, enable).then((res) => {
          _this.handleMessage(res)
          if (res.code === '200') {
            _this.getData()
          }
        })
      },
      editBtnClick(val, type) {
        switch (type) {
          case 'wxCode':
            this.clickUser = val
            getWxappCode(
              'MALL',
              'pages/index/index',
              1,
              {storeUserId: val.storeUserId}).then(res => {
              if (res.code === '200') {
                this.wxAppCode = res.body
                this.dialogVisible = true
              }
            })

            // this.getById(val.userCode)
            break
          case 'switchStatus':
            this.changeEnable(val.storeId, val.storeStatus ? 0 : 1)
            break
        }

      },

      //拉取列表
      getData() {
        pageApi.getPageList(this.pageInfo).then(res => {
          this.columnData = res.body.records
          this.total = Number(res.body.total)
          this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
        })
      },

      changeTab(name) {
        this.pageInfo.pageNumber = 1
        this.pageInfo.enable = name
        this.getData()
      },
      //清空搜索条件
      resetForm() {
        this.pageInfo = {
          pageNum: 1,
          pageSize: 20,
          realName: '',
          storeId: '',
        }
        this.getData()
      },
      getById(id) {
        pageApi.getById(id).then(res => {
          this.form = Object.assign({}, this.form, res.body)
        })
      },
      resetDialogForm() {
        this.form = {
          brandName: '',
          enable: true,
          expressId: null,
          memo: '',
          sort: ''
        }
        this.dialogAdd = false
      },
      handleRes(res) {
        let _this = this
        if (res.code === '200') {
          _this.$message.success(res.message)
          _this.dialogAdd = false
          this.getData()
        } else {
          _this.$message.error(res.message)
        }
      },
      onSubmit() {
        let _this = this
        let {storeId} = _this.form;
        _this.$refs['form'].validate((valid) => {
          if (valid) {
            if (!storeId) {
              pageApi.create(_this.form).then((res) => {
                _this.handleRes(res)
              })
            } else {
              pageApi.update(_this.form).then((res) => {
                _this.handleRes(res)
              })
            }

          } else {
            return false
          }
        })
      },
      getStorelist() {
        getStorelist({}).then(res => {
          this.storeListOptions = res.body
        })
      }
    },
    mounted() {
      this.getData()
      this.getStorelist()
    }
  }
</script>

<style lang="scss" scoped>
  .manage {
    padding: 50px;
  }
</style>
